import pandas as pd
from pyecharts import options as opts
from pyecharts.charts import Map, Bar, Line, Scatter, Liquid, Grid, Pie
from pyecharts.commons.utils import JsCode
from pyecharts.globals import SymbolType


def map_i():
    """ 地图 - 发病率"""
    df_world = pd.read_csv('./data/cancer_world.csv', encoding='gbk')
    map_inum = df_world[['Country', 'Incidence']].values.tolist()

    c = (
        Map(
            init_opts=opts.InitOpts(width="1200px",
                                    height="700px"
                                    )
        )
        .add("总病例数", map_inum, "world")
        .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
        .set_global_opts(
                title_opts=opts.TitleOpts(title="2020年世界癌症确诊总病例数",
                                          subtitle="数据来源：GLOBOCAN",
                                          pos_right="center",
                                          pos_top="4%",
                                          item_gap=5),
                visualmap_opts=opts.VisualMapOpts(max_=100000, range_color=['#E0ECF8', '#045FB4']),
        )
        #     .render("map_world.html")
    )
    return c


def map_m():
    """ 地图 - 死亡率"""
    df_world = pd.read_csv('./data/cancer_world.csv', encoding='gbk')
    map_mnum = df_world[['Country', 'Mortality']].values.tolist()

    c = (
        Map(
            init_opts=opts.InitOpts(width="1200px",
                                    height="700px"
                                    )
        )
        .add("死亡病例数", map_mnum, "world")
        .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
        .set_global_opts(
            title_opts=opts.TitleOpts(title="2020年世界癌症死亡总病例数",
                                      subtitle="数据来源：GLOBOCAN",
                                      pos_right="center",
                                      pos_top="4%",
                                      item_gap=5),
            visualmap_opts=opts.VisualMapOpts(max_=100000,
                                              range_color=['#F6CECE', '#DF0101']),
        )
        #     .render("map_world.html")
    )
    return c


def stackb():
    """ 堆叠柱状图"""
    df_cancer = pd.read_csv('./data/cancer_data.csv', encoding='gbk')
    df_c = df_cancer.sort_values(by='Incidence', ascending=False)[:10]  # 取前10数据
    sta_x = df_c['Cancer'].values.tolist()
    sta_inum = df_c['Incidence'].values.tolist()
    sta_mnum = df_c['Mortality'].values.tolist()

    c = (
        Bar(
            init_opts=opts.InitOpts(width="1200px",
                                    height="700px"
                                    )
        )
        .add_xaxis(sta_x)
        .add_yaxis("发病案例数", sta_inum, stack="stack1")
        .add_yaxis("死亡案例数", sta_mnum, stack="stack1")
        .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
        .set_global_opts(
            title_opts=opts.TitleOpts(
                title="世界发病数前10癌症发病与死亡情况",
                subtitle="数据来源：GLOBOCAN",
                pos_right="center",
                pos_top="5%"
            ))
        #     .render("map_world.html")
    )
    return c


def bar1():
    """ 堆叠柱状图"""
    df_cancer = pd.read_csv('./data/cancer_data.csv', encoding='gbk')
    bar_x = df_cancer['Cancer'].values.tolist()
    bar_fi = df_cancer['F. Incidence'].values.tolist()
    bar_fm = df_cancer['F. Mortality'].values.tolist()

    c = (
        Bar(
            init_opts=opts.InitOpts(width="1200px",
                                    height="700px"
                                    )
        )
        .add_xaxis(bar_x)
        .add_yaxis("发病案例数", bar_fi)
        .add_yaxis("死亡案例数", bar_fm)
        .reversal_axis()
        .set_global_opts(title_opts=opts.TitleOpts(
            title="2020年世界女性患癌情况",
            subtitle="数据来源：GLOBOCAN",
            pos_right="center",
            pos_top="5%"
        ))
        .set_series_opts(
            label_opts=opts.LabelOpts(is_show=False),
            markpoint_opts=opts.MarkPointOpts(
                data=[
                    opts.MarkPointItem(type_="max", name="最大值"),
                    opts.MarkPointItem(type_="min", name="最小值"),
                    #                 opts.MarkPointItem(type_="average", name="平均值"),
                ]
            ),
        )
        #     .render("map_world.html")
    )
    return c


def bar2():
    """ 堆叠柱状图"""
    df_cancer = pd.read_csv('./data/cancer_data.csv', encoding='gbk')
    bar_x = df_cancer['Cancer'].values.tolist()
    bar_mi = df_cancer['M. Incidence'].values.tolist()
    bar_mm = df_cancer['M. Mortality'].values.tolist()

    c = (
        Bar(
            init_opts=opts.InitOpts(width="1200px",
                                    height="700px"
                                    )
        )
        .add_xaxis(bar_x)
        .add_yaxis("发病案例数", bar_mi)
        .add_yaxis("死亡案例数", bar_mm)
        .reversal_axis()
        .set_global_opts(title_opts=opts.TitleOpts(
            title="2020年世界男性患癌情况",
            subtitle="数据来源：GLOBOCAN",
            pos_right="center",
            pos_top="5%"
        ))
        .set_series_opts(
            label_opts=opts.LabelOpts(is_show=False),
            markpoint_opts=opts.MarkPointOpts(
                data=[
                    opts.MarkPointItem(type_="max", name="最大值"),
                    opts.MarkPointItem(type_="min", name="最小值"),
                    #                 opts.MarkPointItem(type_="average", name="平均值"),
                ]
            ),
        )
        #     .render("map_world.html")
    )
    return c


def line_m():
    """ 条形图1 """
    df_lung = pd.read_csv("./data/trends-lung.csv", encoding='gbk')
    temps_l = df_lung.iloc[:, 1:]
    new_c = temps_l.mean(axis=1)
    df_lung.insert(loc=len(df_lung.columns), column='平均值', value=new_c)
    df_l = df_lung.sort_values(by='平均值', ascending=False)[:5]  # 取前5数据

    # x轴数据
    year = list(df_lung)[1:22]
    year_str = list(map(str, year))

    # y轴数据
    temps_l = df_l.iloc[:, 1:22]
    y1_l = temps_l.iloc[0].tolist()
    y2_l = temps_l.iloc[1].tolist()
    y3_l = temps_l.iloc[2].tolist()
    y4_l = temps_l.iloc[3].tolist()
    y5_l = temps_l.iloc[4].tolist()

    c = (
        Line(init_opts=opts.InitOpts(
            width="1200px",
            height="600px"
        )
        )
        .add_xaxis(year_str)
        .add_yaxis("土耳其", y1_l, is_smooth=True, linestyle_opts=opts.LineStyleOpts(color="red"))
        .add_yaxis("波兰", y2_l, is_smooth=True, linestyle_opts=opts.LineStyleOpts(color="blue"))
        .add_yaxis("克罗地亚", y3_l, is_smooth=True, linestyle_opts=opts.LineStyleOpts(color="green"))
        .add_yaxis("白俄罗斯", y4_l, is_smooth=True, linestyle_opts=opts.LineStyleOpts(color="yellow"))
        .add_yaxis("爱沙尼亚", y5_l, is_smooth=True, linestyle_opts=opts.LineStyleOpts(color="purple"))
        .set_series_opts(
            label_opts=opts.LabelOpts(is_show=False),
        )
        .set_global_opts(title_opts=opts.TitleOpts(
            title="1993-2013年世界前5男性肺癌高发国家发病率情况",
            subtitle="数据来源：GLOBOCON",
            pos_right="center",
            pos_top="5%"
        ),
            xaxis_opts=opts.AxisOpts(type_="category", name="年份"),
            yaxis_opts=opts.AxisOpts(name="年龄标准化比率"))
        #     .render("map_world.html")
    )
    return c


def line_f():
    """ 条形图2 """
    df_lung = pd.read_csv("./data/trends-lung.csv", encoding='gbk')
    df_breast = pd.read_csv("./data/trends-breast.csv", encoding='gbk')
    temps_b = df_breast.iloc[:, 1:]  # 取出除国家列以外的数据
    new_c = temps_b.mean(axis=1)  # 求每行平均值
    df_breast.insert(loc=len(df_breast.columns), column='平均值', value=new_c)  # 在表格最后新添平均值列
    df_b = df_breast.sort_values(by='平均值', ascending=False)[:5]  # 取前5数据

    # x轴数据
    year = list(df_lung)[1:22]
    year_str = list(map(str, year))

    # y轴数据
    temps_b = df_b.iloc[:, 1:22]
    y1_b = temps_b.iloc[0].tolist()
    y2_b = temps_b.iloc[1].tolist()
    y3_b = temps_b.iloc[2].tolist()
    y4_b = temps_b.iloc[3].tolist()
    y5_b = temps_b.iloc[4].tolist()

    c = (
        Line(init_opts=opts.InitOpts(
            width="1200px",
            height="600px"
        )
        )
        .add_xaxis(year_str)
        .add_yaxis("法国", y1_b, is_smooth=True, linestyle_opts=opts.LineStyleOpts(color="red"))
        .add_yaxis("荷兰", y2_b, is_smooth=True, linestyle_opts=opts.LineStyleOpts(color="blue"))
        .add_yaxis("丹麦", y3_b, is_smooth=True, linestyle_opts=opts.LineStyleOpts(color="green"))
        .add_yaxis("冰岛", y4_b, is_smooth=True, linestyle_opts=opts.LineStyleOpts(color="yellow"))
        .add_yaxis("意大利", y5_b, is_smooth=True, linestyle_opts=opts.LineStyleOpts(color="purple"))
        .set_series_opts(
            label_opts=opts.LabelOpts(is_show=False),
        )
        .set_global_opts(
            title_opts=opts.TitleOpts(
                title="1993-2013年世界前5女性乳腺癌高发国家发病率情况",
                subtitle="数据来源：GLOBOCON",
                pos_right="center",
                pos_top="5%"),
            xaxis_opts=opts.AxisOpts(type_="category", name="年份"),
            yaxis_opts=opts.AxisOpts(name="年龄标准化比率")
        )
        #     .render("map_world.html")
    )
    return c


def scatter():
    """ 散点图 """
    df = pd.read_csv('./data/estimated-number-from-2020-to-2040.csv', encoding='gbk')

    c = (
        Scatter(
            init_opts=opts.InitOpts(
                width='1200px',
                height='600px'
            )
        )
        .add_xaxis(df['Label'].values.tolist())
        .add_yaxis("2020年", df['2020'].values.tolist())
        .add_yaxis("2040年", df['2040'].values.tolist())
        .set_global_opts(
            title_opts=opts.TitleOpts(
                title="2020-2040年预计新增病例数",
                subtitle="数据来源：GLOBOCON",
                pos_right="center",
                pos_top="4%"),
            visualmap_opts=opts.VisualMapOpts(type_="size", max_=12000000, min_=650000),
        )
        #     .render("scatter_visualmap_size.html")
    )
    return c


def liquid():
    """ 水滴图 """
    l1 = (
        Liquid(
            init_opts=opts.InitOpts(
                width='1200px',
                height='1200px'
            )
        )
        .add("Very High HDI",
             [0.96],
             center=["25%", "30%"],
             is_outline_show=False,
             color=['#DC143C'],
             shape=SymbolType.ARROW)
        .set_global_opts(title_opts=opts.TitleOpts())
    )

    l2 = Liquid().add(
        "High HDI",
        [0.64],
        center=["70%", "30%"],
        is_outline_show=False,
        color=['#FF8C00'],
        shape=SymbolType.ARROW,
        label_opts=opts.LabelOpts(
            font_size=50,
            formatter=JsCode(
                """function (param) {
                        return (Math.floor(param.value * 10000) / 100) + '%';
                    }"""
            ),
            position="inside",
        ),
    )

    l3 = Liquid().add(
        "Medium HDI",
        [0.56],
        center=["25%", "75%"],
        is_outline_show=False,
        color=['#FFD700'],
        shape=SymbolType.ARROW,
        label_opts=opts.LabelOpts(
            font_size=50,
            formatter=JsCode(
                """function (param) {
                        return (Math.floor(param.value * 10000) / 100) + '%';
                    }"""
            ),
            position="inside",
        ),
    )

    l4 = Liquid().add(
        "Low HDI",
        [0.32],
        center=["70%", "75%"],
        is_outline_show=False,
        color=['#32CD32'],
        shape=SymbolType.ARROW,
        label_opts=opts.LabelOpts(
            font_size=50,
            formatter=JsCode(
                """function (param) {
                        return (Math.floor(param.value * 10000) / 100) + '%';
                    }"""
            ),
            position="inside",
        ),
    )

    grid = Grid().add(l1,
                      grid_opts=opts.GridOpts()).add(l2,
                                                     grid_opts=opts.GridOpts()).add(l3,
                                                                                    grid_opts=opts.GridOpts()).add(
        l4, grid_opts=opts.GridOpts())
    return grid


def pie_c():
    """ 饼图 """
    df = pd.read_csv('./data/cause.csv', encoding='gbk')
    df['sum'] = df.iloc[:, 1:].apply(lambda x: sum(x), axis=1)
    pie_s = df[['Cause', 'sum']].values.tolist()

    c = (
        Pie()
        .add("", pie_s)
        .set_global_opts(title_opts=opts.TitleOpts(title="不同诱因导致的癌症病例数",
                                                   pos_right="center",
                                                   pos_top="bottom"))
        .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
        #     .render("pie_base.html")
    )

    return c



def mul_pie():
    """ 多饼图 """
    df = pd.read_csv('./data/cause.csv', encoding='gbk')

    a = df[['Cause', 'Asia']].values.tolist()
    af = df[['Cause', 'Africa']].values.tolist()
    am = df[['Cause', 'The Americas']].values.tolist()
    eu = df[['Cause', 'Europe']].values.tolist()
    oc = df[['Cause', 'Oceania']].values.tolist()

    fn = """
        function(params) {
            if(params.name == '其他')
                return '\\n\\n\\n' + params.name + ' : ' + params.value + '%';
            return params.name + ' : ' + params.value + '%';
        }
        """

    def new_label_opts():
        return opts.LabelOpts(formatter=JsCode(fn), position="center")

    c = (
        Pie()
            .add(
            "",
            a,
            center=["20%", "30%"],
            radius=[60, 80],
            label_opts=new_label_opts(),
        )
            .add(
            "",
            af,
            center=["50%", "30%"],
            radius=[60, 80],
            label_opts=new_label_opts(),
        )
            .add(
            "",
            am,
            center=["10%", "70%"],
            radius=[60, 80],
            label_opts=new_label_opts(),
        )
            .add(
            "",
            eu,
            center=["35%", "70%"],
            radius=[60, 80],
            label_opts=new_label_opts(),
        )
            .add(
            "",
            oc,
            center=["60%", "70%"],
            radius=[60, 80],
            label_opts=new_label_opts(),
        )
            .set_global_opts(
            title_opts=opts.TitleOpts(title="各大洲不同诱因导致的癌症患病案例数",
                                      subtitle="由上至下，从左往右分别是亚洲、非洲、美洲(包括北美洲与南美洲)、欧洲、大洋洲",
                                      pos_left="18%"),
            legend_opts=opts.LegendOpts(
                type_="scroll", pos_top="20%", pos_left="80%", orient="vertical"
            ),
        )
            .set_series_opts(
            label_opts=opts.LabelOpts(is_show=False)
        )
        #     .render("mutiple_pie.html")
    )

    return c


